package cn.tedu.dao;

import cn.tedu.entity.User;
import cn.tedu.utils.DBUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author waqwb
 */
public class UserDao {
    public User getUserByEmail(String email) throws SQLException {
        // 访问数据库
        // 2.获取链接
        Connection connection = DBUtils.getConnection();

        // 3.创建statement并执行sql
        String sql = "SELECT * FROM t_user WHERE email = ?";
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setString(1, email);
        ResultSet resultSet = statement.executeQuery();

        // 4.处理结果集
        User user = null;
        while (resultSet.next()) {
            // 处理
            user = new User();
            user.setId(resultSet.getInt("id"));
            user.setEmail(resultSet.getString("email"));
            user.setNickname(resultSet.getString("nickname"));
            user.setPassword(resultSet.getString("password"));
        }

        // 5.关闭资源
        DBUtils.close(resultSet, statement, connection);

        return user;
    }

    /**
     * 保存用户
     *
     * @param user 用户信息
     * @return 数据库执行sql影响的行数
     * @throws SQLException
     */
    public int saveUser(User user) throws SQLException {

        // 获取链接
        Connection connection = DBUtils.getConnection();

        // 创建statement并执行sql
        String sql = "INSERT INTO t_user (email,nickname,password) VALUES (?,?,?)";
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setString(1, user.getEmail());
        statement.setString(2, user.getNickname());
        statement.setString(3, user.getPassword());
        int row = statement.executeUpdate();

        // 关闭资源
        DBUtils.close(null, statement, connection);

        return row;
    }

}
